package com.example.cyper.osctest;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


public class MainActivity extends Activity {
    private EditText nameText;
    private EditText ageText;
    private Button btnSend;

    private String baseUrl = "http://10.0.2.2:8080/HttpWebServerDemo1/123";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String response = (String) msg.obj;
            Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nameText = (EditText) findViewById(R.id.name);
        ageText = (EditText) findViewById(R.id.age);
        btnSend = (Button) findViewById(R.id.send);

        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String name = nameText.getText().toString();
                final String age = ageText.getText().toString();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String url = String.format("%s?name=%s&age=%s", baseUrl, name, age);
                        HttpGet httpGet = new HttpGet(url);
                        HttpClient httpClient = new DefaultHttpClient();
                        try {
                            HttpResponse httpResponse = httpClient.execute(httpGet);
                            HttpEntity httpEntity = httpResponse.getEntity();
                            String str_result = EntityUtils.toString(httpEntity, "utf-8");
                            Message message = new Message();
                            message.obj = str_result;
                            handler.sendMessage(message);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }


}
